//
//  MemberCenterViewController.swift
//  TinyShopKeeper
//
//  Created by rimi on 16/6/1.
//  Copyright © 2016年 yuying. All rights reserved.
//

import UIKit

class MemberCenterViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate{

    
    @IBOutlet weak var noDataLabel: UILabel!//显示用的label
    
    @IBOutlet weak var mobileTextField: UITextField!//输入框
    
    
    @IBOutlet weak var tableView: UITableView!
     //初始化数据源
    var dataSource:[[String:String]] = [[String:String]]()
    var pageIndex:Int = 1
    var pageSize:Int = 20//"limit": "0,20"
    
    override func viewDidLoad() {
        super.viewDidLoad()
          self.title = "会员信息"
         self.textFieldAddLeftRightView()
        self.addPullPushRefresh()//刷新or加载
        self.tableView .startPullRefresh()//开始下拉刷新，目测头一次点进来还没数据
     }

    
    
    
    //搜索栏的东西
    func textFieldAddLeftRightView(){
        
        let leftView = UIView(frame:CGRectMake(0,0,10,5))
        self.mobileTextField.leftView = leftView
        self.mobileTextField.leftViewMode = UITextFieldViewMode.Always//一直要显示
        
        let rightView = UIView(frame:CGRectMake(0,0,60,55))
        let lineView = UIImageView(frame: CGRectMake(0, 5, 1, 44))
        lineView.image = imageByName("mm_line@2x.png")
        rightView.addSubview(lineView)
        
        let searchBtn = UIButton(type: UIButtonType.Custom)
        searchBtn.frame = CGRectMake(10, 10, 40, 40)
        searchBtn.setImage(imageByName("mm_search@2x.png"), forState: UIControlState.Normal)
        searchBtn.addTarget(self, action:"searchMobile" , forControlEvents: UIControlEvents.TouchUpInside)
        rightView.addSubview(searchBtn)
        
        self.mobileTextField.rightView = rightView
        self.mobileTextField.rightViewMode = UITextFieldViewMode.Always
        self.mobileTextField.attributedPlaceholder = NSAttributedString(string: "输入会员电话..", attributes: [NSForegroundColorAttributeName : ApplicationTintColor])//富文本，设置字体颜色之类
    }
    
    //搜索点击事件
    func searchMobile(){
        
        self.tableView.startPullRefresh()
    }

    
    
    
    
    
    //MSRK:--刷新or加载
    func addPullPushRefresh(){
        
        //~~~~~~会员详细订单列表~~"limit": "0,10",//	从第一条开始，取10条记录（10表示页大小）
        
        //"limit": "0,20"那么~~
        //1下拉刷新~取最新的20条 0，20 ~第一页
        //2上拉加载~再取出20条 20，20 ~第二页
        //3上拉加载~再取出20条 40，20 ~第三页
        
        //下拉刷新~获取到最新的，分页加载每次只加载一部分数据，这次刷，就显示最新的
        self.tableView.addPullRefreshHandler {  [weak self] in
            
            self?.pageIndex = 1;
            self?.loadData(true)//调用下面的方法~判断是下拉刷新还是上拉加载true走
        }
        
        //上拉加载~获取到以前的，分页加载每次只加载一部分数据，这次刷，就显示紧接着的后面的东西
        self.tableView.addPushRefreshHandler { [weak self] in
            
            let currentCount = (self?.pageIndex)! * (self!.pageSize)
            if self?.dataSource.count < currentCount{//╮(╯▽╰)╭分店请求下来的数据就10条，用总店测试呵呵哒
                MBProgressHUD .showError("没有更多数据")//showError一两秒就隐藏了
                self?.tableView.stopPushRefreshEver()//停止上拉加载
            }else{
                self?.pageIndex += 1
                self?.loadData(false)
            }
        }
        
        
        
        
    }
    
    //判断是下拉刷新还是上拉加载
    func loadData(pullSign:Bool){
        var mobile:String = ""
        if self.mobileTextField.text?.characters.count > 0{
            mobile = self.mobileTextField.text!
        }
        
        let location = (pageIndex - 1) * pageSize
        let limitStr = "\(location),\(pageSize)"
        var paramDic = [String:String]()
        paramDic.updateValue(UserInfo.allShopID(), forKey: "shop_id")
        paramDic.updateValue(mobile, forKey: "vip_mobile")
        paramDic.updateValue(limitStr, forKey: "limit")
        //调用拼接的方法
        let urlString = urlAppendGetParams(VIP_LIST_URL)
        
        //网络请求数据
        
        NetTool.requestX("加载中", urlString: urlString, paramDictionary: ["body":paramDic], successAction: { (responseObject) -> Void in
            
            print(responseObject)//得到数据
            
            if pullSign{//下拉刷新ture
                self.dataSource.removeAll()//删了才不会累加
            }
            self.dataSource .appendContentsOf(responseObject["body"] as! [[String:String]])//根据接口文件来，加上数据，这是拼接，所以为了不累加就要先删除
            
            
            //显示隐藏
            if pullSign{
                //下拉刷新
                if self.dataSource.count == 0{
                    //搜索时没有数据
                    self.noDataLabel.hidden = false
                    self.tableView.hidden  = true
                    
                }else{
                    self.noDataLabel.hidden = true
                    self.tableView.hidden  = false
                    
                }
                
            }
            
            
            self.tableView.reloadData()
            MBProgressHUD.showSuccess("加载成功")//改变状态
            if pullSign{//上拉加载false
                self.tableView.stopPullRefreshEver()
            }else{
                self.tableView.stopPushRefreshEver()
            }
            
            }) { (error) -> Void in
                
        }
    }
    
    
    
    
    
    
    //MARK:--Navigation,故事版的点击cell然后show详情页，来传值时需要这个方法
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
        
        //跳到的界面
        let memberDetailVc = segue.destinationViewController as! MemberDetailViewController
        //点击的cell
        let cell = sender as! MemberInfoTableViewCell //这就是点击的cell
        let indexPath = self.tableView.indexPathForCell(cell)//得到cell的indexPath
        
        //属性传值
        let cellSource = self.dataSource[(indexPath?.row)!]
        memberDetailVc.memberSource = cellSource//memberSource是MemberDetialViewController的一个属性
    
        var paramDic:[String:String] = [String:String]()
        paramDic.updateValue(cellSource["shop_id"]!, forKey: "shop_id")
        paramDic.updateValue(cellSource["userId"]!, forKey: "vip_id")
        memberDetailVc.paramDic = paramDic
        memberDetailVc.url = urlAppendGetParams(VIP_DETAIL_LIST_URL)
        memberDetailVc.memberOrHistoryIsOne = true
        

        
    }

    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: -- touch --
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
        
    }

    //MARK:-- 代理方法UITableViewDataSource
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //取消第一响应
        self.mobileTextField.resignFirstResponder()
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return dataSource.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("MemberInfoTableViewCell", forIndexPath: indexPath) as! MemberInfoTableViewCell
        let dic = self.dataSource[indexPath.row]//根据接口写下面的key
        cell.nameLabel.text = dic["vip_nickname"]
        cell.phoneLabel.text = dic["vip_mobile"]
        cell.moneyLabel.text = dic["uvgrade_money"]
        //颜色
        if Int(dic["userSex"]!) == 1{
            cell.nameLabel.textColor = MZColor(99, green: 174, blue: 240)
        }else {
            cell.nameLabel.textColor = MZColor(250, green: 32, blue: 121)
        }
        
        
        return cell
    }

}
